<template>
  <el-dialog
      top="5vh"
      width="1000px"
      title="导入官方参考菜单明细价格表"
      :visible.sync="dialogValue"
      :close-on-click-modal="false"
      append-to-body
  >
    <div class="import-dishes">
      <div class="import-steps">
        <el-steps :active="currentStep" finish-status="success" simple>
          <el-step title="上传Excel文件" icon="el-icon-upload"></el-step>
          <el-step title="预览数据" icon="el-icon-view"></el-step>
          <el-step title="确认导入" icon="el-icon-check"></el-step>
        </el-steps>
      </div>

      <!-- 步骤1：上传Excel文件 -->
      <div v-if="currentStep === 0" class="step-content">
        <h4>请上传官方参考价格Excel文件</h4>
        <div class="upload-area">
          <el-upload
              class="upload-demo"
              drag
              :auto-upload="false"
              :on-change="handleFileChange"
              :before-upload="beforeUpload"
              accept=".xlsx,.xls"
              :show-file-list="false"
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传xlsx/xls文件，且不超过10MB</div>
          </el-upload>
        </div>

        <div class="template-download">
          <h5>Excel模板格式说明：</h5>
          <p>请按照以下列顺序填写数据：</p>
          <ul>
            <li><strong>菜品分类</strong>：如"蔬菜类"、"肉类"等</li>
            <li><strong>菜品名称</strong>：具体的菜品名称</li>
            <li><strong>单位</strong>：如"斤"、"个"、"份"等</li>
            <li><strong>菜品价格</strong>：官方参考价格（数字格式）</li>
          </ul>
          <el-button type="text" @click="downloadTemplate">下载Excel模板</el-button>
          <div style="margin-top: 15px; padding: 10px; background: #e1f3d8; border-radius: 4px;">
            <p style="margin: 0; color: #67c23a;"><strong>当前比价项目：</strong>{{ currentBidding?.title || '未知' }}</p>
            <p style="margin: 5px 0 0 0; color: #67c23a;"><strong>比价月份：</strong>{{ currentBidding?.month || '未知' }}</p>
          </div>
        </div>
      </div>

      <!-- 步骤2：预览数据 -->
      <div v-if="currentStep === 1" class="step-content">
        <h4>预览导入数据</h4>
        <div class="preview-info">
          <p>共解析到 <strong>{{ previewData.length }}</strong> 条菜品数据</p>
        </div>
        <el-table
            size="large"
            stripe
            border
            :data="previewData"
            row-key="rowNumber"
            max-height="400px"
        >
          <el-table-column prop="rowNumber" label="行号" width="80"/>
          <el-table-column prop="category" label="菜品分类" width="150"/>
          <el-table-column prop="name" label="菜品名称" min-width="200"/>
          <el-table-column prop="unit" label="单位" width="100"/>
          <el-table-column prop="base_price" label="菜品价格" width="120">
            <template slot-scope="scope">
              <span v-if="scope.row.status === 'valid'" style="color: #E6A23C; font-weight: bold;">¥{{ scope.row.base_price }}</span>
              <span v-else style="color: #f56c6c;">{{ scope.row.base_price }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="状态" width="100">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status === 'valid'" type="success">有效</el-tag>
              <el-tag v-else type="danger">无效</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="error" label="错误信息" min-width="200">
            <template slot-scope="scope">
              <span v-if="scope.row.error" style="color: #f56c6c;">{{ scope.row.error }}</span>
              <span v-else style="color: #67c23a;">✓</span>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!-- 步骤3：确认导入 -->
      <div v-if="currentStep === 2" class="step-content">
        <h4>确认导入</h4>
        <div class="confirm-info">
          <el-alert
              title="导入确认"
              type="info"
              :closable="false"
              show-icon>
              <div slot="description">
                <p>将向比价项目 <strong>{{ selectedBidding?.title }}</strong> 导入 <strong>{{ validDataCount }}</strong> 条菜品官方参考价格数据</p>
                <p>导入后将覆盖该比价项目的现有菜品数据</p>
              </div>
            </el-alert>
        </div>
      </div>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button @click="prevStep" v-if="currentStep > 0">上一步</el-button>
      <el-button @click="dialogValue = false">取消</el-button>
      <el-button type="primary" @click="nextStep" v-if="currentStep < 2">下一步</el-button>
      <el-button type="success" :loading="importLoading" @click="confirmImport" v-if="currentStep === 2">确认导入</el-button>
    </div>

    <!-- 菜品明细列表弹窗 -->
    <DishList ref="dishListRef" />
  </el-dialog>
</template>

<script>
import { http, uploadFile } from '@/api';
import { downloadDishPriceTemplate } from '@/utils/excelTemplate';
import DishList from './dishList';

export default {
  name: 'ImportDishes',
  components: {
    DishList
  },
  data() {
    return {
      dialogValue: false,
      loading: false,
      currentStep: 0,
      currentBidding: null,
      uploadedFile: null,
      previewData: [],
      validDataCount: 0,
      importLoading: false
    };
  },
  methods: {
    open(biddingInfo) {
      this.dialogValue = true;
      this.currentStep = 0;
      this.currentBidding = biddingInfo;
      this.uploadedFile = null;
      this.previewData = [];
    },

    showDishList(biddingInfo) {
      this.$refs.dishListRef.open(biddingInfo);
    },

    nextStep() {
      if (this.currentStep === 0) {
        if (!this.uploadedFile) {
          this.$message.warning('请先上传Excel文件');
          return;
        }
      }
      if (this.currentStep === 1) {
        if (this.validDataCount === 0) {
          this.$message.warning('没有有效的数据可以导入');
          return;
        }
      }
      this.currentStep++;
    },
    prevStep() {
      this.currentStep--;
    },
    beforeUpload(file) {
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
                      file.type === 'application/vnd.ms-excel';
      const isLt10M = file.size / 1024 / 1024 < 10;

      if (!isExcel) {
        this.$message.error('只能上传Excel文件!');
        return false;
      }
      if (!isLt10M) {
        this.$message.error('文件大小不能超过10MB!');
        return false;
      }
      return true;
    },
    handleFileChange(file) {
      if (!file) return;

      const reader = new FileReader();
      reader.onload = (e) => {
        try {
          this.uploadedFile = e.target.result;
          // this.$message.success('文件读取成功');
          this.parseExcelData();
        } catch (error) {
          console.error('文件读取失败:', error);
          this.$message.error('文件读取失败');
        }
      };
      reader.onerror = () => {
        this.$message.error('文件读取失败');
      };
      reader.readAsArrayBuffer(file.raw);
    },
    async parseExcelData() {
      try {
        // 动态导入XLSX
        const XLSX = await import('xlsx');

        // 从上传的文件数据中解析Excel
        const workbook = XLSX.read(this.uploadedFile, { type: 'array' });
        const sheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[sheetName];

        // 将工作表转换为JSON数据
        const rawData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });

        // 验证表头
        const headers = rawData[0];
        const expectedHeaders = ['菜品分类', '菜品名称', '单位', '菜品价格'];

        console.log('解析到的表头:', headers);
        console.log('期望的表头:', expectedHeaders);

        if (!this.validateHeaders(headers, expectedHeaders)) {
          this.$message.error('Excel文件格式不正确，请使用正确的模版格式');
          return;
        }

        // 解析数据行
        const parsedData = [];
        console.log('原始数据行数:', rawData.length);

        for (let i = 1; i < rawData.length; i++) {
          const row = rawData[i];
          console.log(`第${i + 1}行数据:`, row);

          if (row.length === 0 || row.every(cell => !cell)) {
            console.log(`第${i + 1}行为空行，跳过`);
            continue; // 跳过空行
          }

          const dishData = this.parseRow(row, i + 1);
          if (dishData) {
            parsedData.push(dishData);
          }
        }

        this.previewData = parsedData;
        this.validDataCount = this.previewData.filter(item => item.status === 'valid').length;
        this.invalidDataCount = this.previewData.filter(item => item.status === 'invalid').length;

        this.$message.success(`成功解析 ${this.validDataCount} 条有效数据，无效数据${this.invalidDataCount} 条无效数据条`);

        // 自动跳转到预览数据页面
        this.currentStep = 1;

      } catch (error) {
        console.error('解析Excel文件失败:', error);
        this.$message.error('解析Excel文件失败: ' + error.message);
      }
    },

    validateHeaders(headers, expectedHeaders) {
      if (!headers || headers.length < expectedHeaders.length) {
        return false;
      }

      for (let i = 0; i < expectedHeaders.length; i++) {
        if (headers[i] !== expectedHeaders[i]) {
          return false;
        }
      }

      return true;
    },

    parseRow(row, rowNumber) {
      try {
        const [category, name, unit, price] = row;
        const numPrice1 = parseFloat(price);
        return {
          category: category.trim(),
          name: name.trim(),
          unit: unit.trim(),
          base_price: isNaN(numPrice1) ? 0 : numPrice1,
          status: 'valid',
          rowNumber
        };

        return
        // 验证必填字段
        if (!category || !name || !unit || !price) {
          return {
            category: category || '',
            name: name || '',
            unit: unit || '',
            base_price: price || 0,
            status: 'invalid',
            error: '必填字段不能为空',
            rowNumber
          };
        }

        // 验证价格格式
        const numPrice = parseFloat(price);
        if (isNaN(numPrice) || numPrice <= 0) {
          return {
            category,
            name,
            unit,
            base_price: price,
            status: 'invalid',
            error: '价格必须是大于0的数字',
            rowNumber
          };
        }

        // 验证字符串长度
        if (category.length > 50 || name.length > 100 || unit.length > 20) {
          return {
            category,
            name,
            unit,
            base_price: numPrice,
            status: 'invalid',
            error: '字段长度超出限制',
            rowNumber
          };
        }

        return {
          category: category.trim(),
          name: name.trim(),
          unit: unit.trim(),
          base_price: numPrice,
          status: 'valid',
          rowNumber
        };

      } catch (error) {
        return {
          category: row[0] || '',
          name: row[1] || '',
          unit: row[2] || '',
          base_price: row[3] || 0,
          status: 'invalid',
          error: '数据格式错误',
          rowNumber
        };
      }
    },
    async downloadTemplate() {
      try {
        await downloadDishPriceTemplate();
        this.$message.success('模板下载成功');
      } catch (error) {
        console.error('下载模版失败:', error);
        this.$message.error('模板下载失败: ' + error.message);
      }
    },
    confirmImport() {
      if (!this.currentBidding || !this.uploadedFile) {
        this.$message.error('数据不完整，无法导入');
        return;
      }
      // 提示确认对话框，导入会覆盖之前导入的数据
      this.$confirm('如果已导入过数据，本次导入会覆盖之前导入的数据，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.importData();
      });
    },
    importData() {
      const importData = {
        monthly_bidding_id: this.currentBidding.id,
        dishes: this.previewData.filter(item => item.status === 'valid')
      };
      console.log(importData.dishes.map(item => item.base_price))
      this.importLoading = true
      // 调用后端接口导入数据
      http.dish.batchCreate(importData).then(() => {
        this.$message.success('官方参考价格导入成功');
        this.dialogValue = false;
        this.$emit('get-page');
      }).finally(() => {
        this.importLoading = false
      })
    }
  }
};
</script>

<style scoped lang="scss">
.import-dishes {
  .import-steps {
    margin-bottom: 30px;
  }

  .step-content {
    h4 {
      margin-bottom: 20px;
      color: #303133;
    }
  }

  .upload-area {
    margin-bottom: 30px;
  }

  .template-download {
    background: #f5f7fa;
    padding: 20px;
    border-radius: 4px;

    h5 {
      margin-bottom: 10px;
      color: #303133;
    }

    ul {
      margin: 10px 0;
      padding-left: 20px;
    }

    li {
      margin-bottom: 5px;
    }
  }

  .preview-info {
    margin-bottom: 20px;
  }

  .confirm-info {
    margin-bottom: 20px;
  }
}



.dialog-footer {
  text-align: right;
}
</style>
